package com.ruanyun.modular.ry.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruanyun.base.pojo.page.LayuiPageFactory;
import com.ruanyun.base.pojo.page.LayuiPageInfo;
import com.ruanyun.modular.ry.api.vo.req.AddressInsertReq;
import com.ruanyun.modular.ry.api.vo.req.AddressUpdateReq;
import com.ruanyun.modular.ry.api.vo.resp.AddressRespVo;
import com.ruanyun.modular.ry.common.PublicCommon;
import com.ruanyun.modular.ry.entity.Address;
import com.ruanyun.modular.ry.mapper.AddressMapper;
import com.ruanyun.modular.ry.model.params.AddressParam;
import com.ruanyun.modular.ry.model.result.AddressResult;
import com.ruanyun.modular.ry.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 地址表 服务实现类
 * </p>
 *
 * @author conan
 * @since 2020-12-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

    @Override
    public void add(AddressParam param){
        Address entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(AddressParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(AddressParam param){
        Address oldEntity = getOldEntity(param);
        Address newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public AddressResult findBySpec(AddressParam param){
        return null;
    }

    @Override
    public List<AddressResult> findListBySpec(AddressParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(AddressParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(AddressParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Address getOldEntity(AddressParam param) {
        return this.getById(getKey(param));
    }

    private Address getEntity(AddressParam param) {
        Address entity = new Address();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 添加地址
     *
     * @param addressInsertReq
     * @return
     */
    @Override
    public ResponseData insertAddress(AddressInsertReq addressInsertReq, Long customerId) {
        Address address = new Address();
        BeanUtils.copyProperties(addressInsertReq, address);
        List<Address> addressList = this.baseMapper.selectList(Wrappers.<Address>lambdaQuery().eq(Address::getCustomerId, customerId).ne(Address::getDelFlag, PublicCommon.DEL_FLAG_DELETE));
        if (CollectionUtil.isEmpty(addressList)) {
            address.setIsDefault(1);
        } else {
            Address resultAddress = addressList.stream().filter(x -> x.getIsDefault().intValue() == 1).findAny().orElse(null);
            if (resultAddress == null) {
                address.setIsDefault(1);
            } else {
                if (addressInsertReq.getIsDefault().intValue() == 1) {
                    resultAddress.setIsDefault(0);
                    this.baseMapper.updateById(resultAddress);
                    address.setIsDefault(1);
                } else {
                    address.setIsDefault(0);
                }
            }
        }
        address.setDelFlag(PublicCommon.DEL_FLAG_NORMAL);
        address.setCreateTime(new Date());
        address.setCustomerId(customerId);
        int insertCount = this.baseMapper.insert(address);
        if (insertCount == 0) {
            return ResponseData.error("地址保存失败");
        }
        return ResponseData.success();
    }

    /**
     * 修改地址
     *
     * @param addressUpdateReq
     * @param customerId
     * @return
     */
    @Override
    public ResponseData updateAddress(AddressUpdateReq addressUpdateReq, Long customerId) {
        Address address = this.baseMapper.selectById(addressUpdateReq.getId());
        if (address == null) {
            return ResponseData.error("该用户地址不存在");
        }
        if (address.getIsDefault().intValue() == 1) {
            addressUpdateReq.setIsDefault(1);
        } else {
            if (addressUpdateReq.getIsDefault().intValue() == 1) {
                Address resultAddress = this.baseMapper.selectOne(Wrappers.<Address>lambdaQuery().eq(Address::getCustomerId, customerId).eq(Address::getIsDefault, 1).ne(Address::getDelFlag, PublicCommon.DEL_FLAG_DELETE));
                if (resultAddress == null) {
                    addressUpdateReq.setIsDefault(1);
                } else {
                    resultAddress.setIsDefault(0);
                    this.baseMapper.updateById(resultAddress);
                    addressUpdateReq.setIsDefault(1);
                }
            }
        }
        BeanUtils.copyProperties(addressUpdateReq, address);
        address.setUpdateTime(new Date());
        int insertCount = this.baseMapper.updateById(address);
        if (insertCount == 0) {
            return ResponseData.error("地址修改失败");
        }
        return ResponseData.success();
    }

    /**
     * 列表查询带分页
     *
     * @param customerId
     * @return
     */
    @Override
    public ResponseData findPage(Integer current, Integer size, Long customerId) {
        IPage<AddressRespVo> page = this.baseMapper.findPage(new Page(current, size), customerId);
        return ResponseData.success(page);
    }

    /**
     * 删除地址
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData deleteAddressById(Long id) {
        Address address = this.baseMapper.selectById(id);
        if (address == null) {
            return ResponseData.error("地址不存在");
        }
        address.setDelFlag(PublicCommon.DEL_FLAG_DELETE);
        int delCount = this.baseMapper.updateById(address);
        if (delCount == 0) {
            return ResponseData.error("删除地址失败");
        }
        return ResponseData.success();
    }

    /**
     * 获取用户默认地址
     *
     * @param customerId
     * @return
     */
    @Override
    public ResponseData getDefaultAddressByCustomerId(Long customerId) {
        Address address = this.baseMapper.selectOne(Wrappers.<Address>lambdaQuery().eq(Address::getIsDefault, 1).eq(Address::getCustomerId, customerId).eq(Address::getDelFlag, PublicCommon.DEL_FLAG_NORMAL));
        AddressRespVo addressRespVo = new AddressRespVo();
        if (address != null) {
            BeanUtils.copyProperties(address, addressRespVo);
        }
        return ResponseData.success(addressRespVo);
    }
}
